<template>
  <div>
    <!-- <slot name="before"></slot>
    <slot name="after"></slot>
    <slot name="loading">
      <div class="loading"></div>
    </slot> -->
    <audio v-if="playerType === 'audio'" :src="src" class="player" :controls="controls" :autoplay="autoplay" :loop="loop" @loadedmetadata="loadedmetadata">
      Your browser does not support the audio tag.
    </audio>
    <video v-else-if="playerType === 'video'" :src="src" class="player" :controls="controls" :autoplay="autoplay" :loop="loop" @loadedmetadata="loadedmetadata">
      Your browser does not support the video tag.
    </video>
  </div>
</template>

<script>
  export default {
    name: 'Player',
    props: {
      src: {
        type: String
      },
      controls: {
        type: Boolean,
        default: true
      },
      autoplay: {
        type: Boolean,
        default: false
      },
      loop: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        playerType: this.getType()
      }
    },
    methods: {
      getType () {
        if (/.mp3$/.test(this.src)) {
          return 'audio'
        } else if (/.mp4$/.test(this.src)) {
          return 'video'
        }
      },
      loadedmetadata () {
        this.$emit('duration', this.$refs.player.duration)
      }
    }
  }
</script>

<style scoped>
  .loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .loading:after {
    content: 'Loading...';
  }
  .player {
    width: 400px;
    height: 300px;
    background-color: black;
    color: white;
  }
</style>